#include <rtdbg.h>
#include "rtthread.h"
#include "sys/socket.h"   /*使用BSD Socket，需要包含socket.h*/
#include "netdb.h"
#include "string.h"
#include "finsh.h"
#define PORT 5001


static const char send_data[]="This is TCP Server";
static rt_thread_t tcp_server_thread_ptr = RT_NULL;

void tcp_server_thread(void* parameter)
{ 
	int sock=-1;
	int connected;
	int recv_data_len;
	char rbuff_TP[512]={0};
	/* LWIP_IPV4 */
	struct sockaddr_in server_addr,client_addr;
	//struct hostent *host;
	while(1)
	{
		if((sock=socket(AF_INET,SOCK_STREAM,0))==-1)   /*创建socket*/
		{  
			LOG_E("socket error");
			return;
		}
		
		/*初始化预连接的服务器地址*/
		server_addr.sin_family=AF_INET;
		server_addr.sin_port=htons(PORT);
		server_addr.sin_addr.s_addr = INADDR_ANY;
		rt_memset(&(server_addr.sin_zero),0,sizeof(server_addr.sin_zero));

		/*连接到服务器*/
		if(bind(sock,(struct sockaddr*)(&server_addr),sizeof(struct sockaddr))==-1)
		{
			LOG_E("unable to bind");
			closesocket(sock);
			rt_thread_mdelay(50);
			continue;
			//return;
		}
		else
		{
			LOG_I("bind successful");
		}
		/*监听，维护两个队列，一个是完成三次握手的，一个是没完成三次握手的*/
		if(listen(sock,5)==-1)
		{
			LOG_E("Listen error");
			closesocket(sock);
			rt_thread_mdelay(500);
			continue;
		}else{LOG_I("Listen successful");}
		
		/*为每个连接创建新的套接字，并从监听队列中移除这个连接*/
		socklen_t sin_size = sizeof(struct sockaddr);	
		if((connected=accept(sock,(struct sockaddr*)&client_addr,&sin_size))==-1)
		{//返回新创建的套接字描述符
			LOG_E("accept fail");
		}
		else{LOG_I("accept success");}
		
		/*网络字U32转换为4字节地址,网络字节顺序转换为主机字节顺序*/
		LOG_I("new client connect from(%s,%d)",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));
		{
			int flag =1;
     	setsockopt(connected,
      					IPPROTO_TCP,  /*设置为TCP层选项*/
								TCP_NODELAY,  /*选项名称*/
 								(void*)&flag, /*选项值*/
								sizeof(int)); /*选项值的长度*/
		}
		while (1)
		{	
			int ret;
			ret=send(connected,send_data,strlen(send_data),0);
			if (ret<=0)
			{
				LOG_E("server send error,close the socket");
				closesocket(connected);
				closesocket(sock);
				break;
			}
			recv_data_len= recv(connected,rbuff_TP,sizeof(rbuff_TP), 0);
			if(recv_data_len<0)
			{
				LOG_E("received error,close the socket");
				closesocket(connected);
				closesocket(sock);
				break;
			}

			else if(recv_data_len==0)
			{//目标地址已完成传输，并关闭连接
				LOG_W("received warning,recv function return 0");
				closesocket(connected);
				closesocket(sock); 
				break;
			}
			
			/*有收到数据，把末尾清零*/
			rbuff_TP[recv_data_len]='\0';
			if(strncmp(rbuff_TP,"q",1)==0||strncmp(rbuff_TP,"Q",1)==0)
			{
				LOG_W("recv a 'q' or 'Q' ,server close the socket");
				closesocket(connected);
				closesocket(sock);
				break;
			}
			else
			{/*在终端显示收到的数据*/
				LOG_I("receive data = |%s|",rbuff_TP);
			}
			rt_thread_mdelay(50);
		}
	}
}
	
int tcp_server_thread_new(void)
{
	tcp_server_thread_ptr = rt_thread_create("tcpserver_th",tcp_server_thread,
							RT_NULL,1536,12,20);
	if(tcp_server_thread_ptr!=RT_NULL)
	{
		rt_thread_control(tcp_server_thread_ptr,RT_THREAD_CTRL_STARTUP,0);
	}
	return 0;
}
	


